#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
#include <math.h>
#include <algorithm>
#include <string>
#include <stack>
using namespace std;
  struct ListNode {
      int val;
    ListNode *next;
     ListNode(int x) : val(x), next(NULL) {}
 };

ListNode* reverse(ListNode* head) {
    ListNode *last= nullptr;
    ListNode *current=head;
    ListNode *next= nullptr;
    while(current!= nullptr){
        next=current->next;
        current->next=last;
        last=current;
        current=next;
    }
    return last;
}
ListNode* reverseKGroup(ListNode* head, int k) {
    ListNode*current= new ListNode(0);
    current->next=head;
    ListNode*last= current;
    ListNode*end= current;
    ListNode*start= nullptr;
    ListNode*next= nullptr;
    while(end->next!= nullptr){
        cout<<"here"<<endl;
        for(short i=0;i<k&&end!= nullptr;i++)end=end->next;
        if(end== nullptr)break;
        next=end->next;
        end->next= nullptr;
        start=last->next;
        last->next=reverse(start);
        start->next=next;
        last=start;
        end=last;
    }
    return current->next;
}
int main(){
    ListNode* temp;
    ListNode* a1=new ListNode(1);
    temp=a1;
    temp->next=new ListNode(2);
    temp=temp->next;
    temp->next=new ListNode(3);
    temp=temp->next;
    temp->next=new ListNode(4);
    temp=temp->next;
    temp->next=new ListNode(5);

    ListNode*result=reverseKGroup(a1,2);
    while(result!= nullptr){
        cout<<result->val<<",";
        result=result->next;
    }
    return 0;
}